package com.cedar.mybatisPlus.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cedar.mybatisPlus.entity.Users;
import com.cedar.mybatisPlus.mapper.UserMapper;
import com.cedar.mybatisPlus.service.impl.UserServiceImpl;

@RestController
public class UserContorller {
	@Autowired
	UserMapper userMapper;
	@Autowired
	UserServiceImpl userServiceImpl;

	private <T> void print(List<T> list) {
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(System.out::println);
        }
    }
	
	
	@RequestMapping(value="/getUserList")
	public void getUserList(){
		System.out.println("-----查询开始-----");
		
		/**条件构造器**/
		/*相当于 id=1 */
		QueryWrapper<Users> qw = new QueryWrapper<Users>();
		Map<String,Object> map = new HashMap<>();
		map.put("id", 1);
		//qw.ne("id", 2);//id != 2
		/*gt大于;ge大于等于;lt小于;le小于等于*/
		//qw.between("id", 2, 4);//id between 18 and 30
		qw.allEq(map);
		
        List<Users> userList = userMapper.selectList(qw);
        for (Users users : userList) {
        	System.out.println(users.getId()+users.getUsername()+users.getRemarks());
		}
	}
	
	/**分页插件*/
	@RequestMapping(value="/getUserByPage")
	public void getUserByPage() {
		Page<Users> page = new Page<>(1, 2);
//		userServiceImpl.selectPageVo(page, 1);
		
		IPage<Users> selectPage = userMapper.selectPage(page, new QueryWrapper<Users>().eq("age", 18));
		
		System.out.println("总记录数"+selectPage.getTotal());
		System.out.println("当前页"+selectPage.getCurrent());
		System.out.println("当前每页显示数"+selectPage.getSize());
		List<Users> list = selectPage.getRecords();
		print(selectPage.getRecords());
	}
	
	/**XML 自定义分页*/
	@RequestMapping(value="/getUserByMyPage")
	public void getUserByMyPage() {
		Page<Users> page = new Page<>(1, 2);
		IPage<Users> selectPage = userServiceImpl.selectPageVo(page, 1);
		
		System.out.println("总记录数"+selectPage.getTotal());
		System.out.println("当前页"+selectPage.getCurrent());
		System.out.println("当前每页显示数"+selectPage.getSize());
		List<Users> list = selectPage.getRecords();
		print(selectPage.getRecords());
	}
}
